package com.usian.user.filter;

import com.usian.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.config.Order;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Fay
 * @date 2022/7/18&11:12
 */
@Order(1)
@Slf4j
@WebFilter(filterName = "appTokenFilter",urlPatterns = "/api/*")
public class AppTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        String userId = request.getHeader("userId");
        log.info("请求头中的id为"+userId);
        //如果userId为0，说明当前设备没有登录
        if (!StringUtils.isEmpty(userId) && Integer.valueOf(userId).intValue() != 0) {
//            把用户输入放入ThreadLocal中
            UserThreadLocalUtils.setUserId(Integer.valueOf(userId));
        }
        chain.doFilter(req, res);
    }
}
